package com.tingyuge.think.in.lucene.test;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.nio.file.Paths;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/7/25
 */
public class LuceneIndexManager {
    @Test
    public void indexCreate() throws Exception {
    // 创建分词器
        Analyzer analyzer = new StandardAnalyzer();
        // 创建Directory流对象
        Directory directory = FSDirectory.open(Paths.get("D:/lucene/index3"));
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        // 创建写入对象
        IndexWriter indexWriter = new IndexWriter(directory, config);
        // 创建Document
        Document document = new Document();
        document.add(new TextField("id", "1001", Field.Store.YES));
        document.add(new TextField("name", "game", Field.Store.YES));
        document.add(new TextField("desc", "one world one dream", Field.Store.NO));
        // 添加文档 完成索引添加
        long l = indexWriter.addDocument(document);
        // 释放资源
        indexWriter.close();
    }

    @Test
    public void indexDelete ()throws Exception{
        Analyzer analyzer = new StandardAnalyzer();
        FSDirectory directory = FSDirectory.open(Paths.get("D:/lucene/index3"));
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter indexWriter = new IndexWriter(directory,config);
        long l = indexWriter.deleteDocuments(new Term("name", "game"));
        System.out.println(l);
        indexWriter.close();
    }

    @Test
    public void indexUpdate() throws Exception {
    // 创建分词器
        Analyzer analyzer = new StandardAnalyzer();
    // 创建Directory流对象
        Directory directory = FSDirectory.open(Paths.get("D:/lucene/index3"));
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
    // 创建写入对象
        IndexWriter indexWriter = new IndexWriter(directory, config);
    // 创建Document
        Document document = new Document();
        document.add(new TextField("id", "1002", Field.Store.YES));
        document.add(new TextField("name", "lucene测试test update1003",  Field.Store.YES));
    // 执行更新，会把所有符合条件的Document删除，再新增。
        indexWriter.updateDocument(new Term("name", "test"), document);
    // 释放资源
        indexWriter.close();
    }
}
